#include <SnakeLib/Problem.h>

#include "MySolver.h"

using namespace snake;



EDirection MySolver::Solve(const snake::Problem &problem)
{
auto board = problem.GetBoard();
int corner = MySolver::isInCorner(board);
EDirection move = UP;
switch (corner)
	{
	case 1 : 
		{
		auto head_position = MySolver::headPosition(board);
		ECellContents head_orient = board.GetCell(head_position.first , head_position.second);
		if (head_orient == ECellContents::CELL_SNAKE_HEAD_UP)
			{	
			return RIGHT;
			}
		else 
			{
			return DOWN;
			}
		}
	}


return move;
}

int MySolver::isInCorner(snake::Board& board)
	{
	int width = board.GetWidth();
	int height = board.GetHeight();
	std::pair<int, int> head = MySolver::headPosition(board);

		if (head.first == 1 && head.second == 1)
			return 1;
		else if (head.first == width - 2 && head.second == 1)
			return 2;
		else if (head.first == width - 2 && head.second == height - 2)
			return 3;
		else if(head.first == 1 && head.second == height - 2)
			return 4;
		else 
			return 0;
	}

std::pair<int, int> MySolver::headPosition(snake::Board& board)
	{
	int width = board.GetWidth();
	int height = board.GetHeight();
	std::pair<int, int> head = std::make_pair(-1,-1);

	for(int i = 0; i < height; ++i)
		for (int j = 0; j  < width; j ++)
			{
			ECellContents cell = board.GetCell(j, i);
			if(cell == CELL_SNAKE_HEAD_DOWN || cell == CELL_SNAKE_HEAD_LEFT || cell == CELL_SNAKE_HEAD_RIGHT || cell == CELL_SNAKE_HEAD_UP)
				{
				head = std::make_pair(j, i);
				}
			}
		return head;
	}

std::pair<int, int> MySolver::foodPosition(snake::Board& board)
	{
		int width = board.GetWidth();
	int height = board.GetHeight();
	std::pair<int, int> head = std::make_pair(-1,-1);

	for(int i = 0; i < height; ++i)
		for (int j = 0; j  < width; j ++)
			{
			ECellContents cell = board.GetCell(j, i);
			if(cell == CELL_FOOD)
				{
				head = std::make_pair(j, i);
				}
			}
		return head;
	}